package com.yuexun.beilunpatient.ui.contractmanage.ui.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yuexun.beilunpatient.R;
import com.yuexun.beilunpatient.base.BaseEntity;
import com.yuexun.beilunpatient.config.AppConfig;
import com.yuexun.beilunpatient.ui.inspect.adapter.InspectListAdapter;
import com.yuexun.beilunpatient.ui.inspect.bean.CheckRow;
import com.yuexun.beilunpatient.ui.inspect.bean.CheckRowSet;
import com.yuexun.beilunpatient.ui.inspect.model.impl.InspectModel;
import com.yuexun.beilunpatient.ui.inspect.presenter.impl.InspectListPresenter;
import com.yuexun.beilunpatient.ui.inspect.ui.Act_Inspect_Detail;
import com.yuexun.beilunpatient.ui.inspect.ui.view.IInspectListView;
import com.yuexun.beilunpatient.utils.AgeUtil;
import com.yuexun.beilunpatient.utils.ScreenUtil;
import com.yuexun.beilunpatient.widget.EmptyLayout;
import com.yuexun.beilunpatient.widget.PullToRefresh.FooterLoadingLayout;
import com.yuexun.beilunpatient.widget.PullToRefresh.PullToRefreshBase;
import com.yuexun.beilunpatient.widget.PullToRefresh.PullToRefreshList;
import com.yuexun.library.AbstractWheel;
import com.yuexun.library.OnWheelChangedListener;
import com.yuexun.library.adapters.ArrayWheelAdapter;

import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.SystemTool;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenss on 2018/3/30 0030.
 */

public class Frag_Inspection extends KJFragment implements IInspectListView {
    @Bind(R.id.content_list)
    PullToRefreshList contentList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.select_tv)
    TextView selectTv;
    @Bind(R.id.select_ll)
    RelativeLayout selectLl;

    private ListView mList;
    private InspectListPresenter presenter;
    List<CheckRow> datas = new ArrayList<>();
    InspectListAdapter adapter;
    private int nowpage = 1;
    private int pagesize = 20;

    String[] years = new String[]{};
    int agePosition = 0;
    String startDate ="",endDate="";

    //判断是否正在显示
    protected boolean isVisible;

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View view = inflater.inflate(R.layout.frag_list, null);
        ButterKnife.bind(this, view);
        isVisible = true;
        return view;
    }

    @Override
    protected void initData() {
        selectLl.setVisibility(View.VISIBLE);
        presenter = new InspectListPresenter(this, new InspectModel());
        ApiGetData(startDate,endDate);
        listViewPreference();
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        years = AgeUtil.getAge(year,"最近两");
    }

    /**
     * 请请求数据
     */
    private void ApiGetData(String startDate,String endDate) {
        if (SystemTool.checkNet(getActivity())) {
            Map<String, String> params = new HashMap<>();
            params.put("sessionUuidPatient", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
            params.put("cardNo", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.ID_CARD));
//            params.put("endDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
//            params.put("startDate", new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.getDateBefore(new Date(), 3)));
            params.put("pageIndex", nowpage + "");
            params.put("pageSize", pagesize + "");
            params.put("startDate", startDate);
            params.put("endDate", endDate);
            presenter.inquireCheckPageList(params);
        } else {
            ViewInject.toast("网络异常，请检查网络是否连接!");
        }
    }

    /**
     * 初始化ListView样式
     */
    private void listViewPreference() {
        mList = contentList.getRefreshView();
        mList.setDivider(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
        mList.setOverscrollFooter(null);
        mList.setOverscrollHeader(null);
        mList.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        contentList.setPullRefreshEnabled(true);
        contentList.setPullLoadEnabled(true);
        ((FooterLoadingLayout) contentList.getFooterLoadingLayout()).setNoMoreDataText("已经是最新状态");

        adapter = new InspectListAdapter(mList, datas, R.layout.item_inspectlist);
        mList.setAdapter(adapter);

        mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CheckRow item = (CheckRow) parent.getItemAtPosition(position);

                if (item.getApply_no() != null && !item.getApply_no().isEmpty()) {
                    Bundle bundle = new Bundle();
                    bundle.putString("applyNo", item.getApply_no());
                    bundle.putString("hospId", item.getHosp_id());
                    bundle.putString("regTime", item.getReg_dtime());
                    Intent intent = new Intent(getActivity(), Act_Inspect_Detail.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    ViewInject.toast("未出报告单!");
                }
            }
        });

        contentList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                nowpage = 1;
                ApiGetData(startDate,endDate);
            }

            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                nowpage = nowpage + 1;
                ApiGetData(startDate,endDate);
            }
        });

        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                nowpage = 1;
                ApiGetData(startDate,endDate);
            }
        });
    }

    @Override
    public void showInspectList(BaseEntity<CheckRowSet> bean) {
        if(isVisible){
            if (contentList.isPullRefreshEnabled()) {
                contentList.onPullDownRefreshComplete();
            }
            if (bean.getStatus().equals("200")) {
                if(bean.getDatas().get(0).getCode() == 1){
                    if (bean.getDatas().get(0).getRows().size() == 0) {
                        contentList.setHasMoreData(false);
                    } else {
                        if (contentList.isPullLoadEnabled()) {
                            contentList.onPullUpRefreshComplete();
                        }
                    }

                    if (nowpage == 1) {
                        datas.clear();
                        datas = bean.getDatas().get(0).getRows();
                    } else {
                        datas.addAll(bean.getDatas().get(0).getRows());
                    }
                    adapter.refresh(datas);
                }else {
                    ViewInject.toast(bean.getDatas().get(0).getDesc());
                }

            }else {
                ViewInject.toast(bean.getMessage());
            }

            if (datas.size() == 0) {
                emptyLayout.setErrorType(EmptyLayout.NODATA);
            } else {
                emptyLayout.dismiss();
            }
        }

    }

    private void ageDialog() {
        final Dialog dialog = new Dialog(getActivity(), R.style.dialog4style);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.picker_content, null);
        view.findViewById(R.id.picker_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.picker_done).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initSearch();
                dialog.dismiss();
            }
        });

        final AbstractWheel zone = (AbstractWheel) view.findViewById(R.id.wheel);
        zone.setVisibleItems(3);
//        zone.setCyclic(true);
        ArrayWheelAdapter<String> adapter =
                new ArrayWheelAdapter<String>(getActivity(), years);
        adapter.setTextSize(18);
        zone.setViewAdapter(adapter);
        zone.setCurrentItem(agePosition);
        zone.addChangingListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(AbstractWheel wheel, int oldValue, int newValue) {
                agePosition = newValue;
            }
        });

        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = ScreenUtil.getScreenWidth(getActivity());
        params.gravity = Gravity.BOTTOM;
        dialog.getWindow().setAttributes(params);
        dialog.getWindow().setWindowAnimations(R.style.dialog_anim_style);
        dialog.show();
    }

    private void initSearch() {
        selectTv.setText(years[agePosition]+"年");
        if(agePosition == 0)
        {
            startDate="";
            endDate = "";
        }
        else {
            startDate=years[agePosition]+"-01-01 00:00:00";
            endDate=years[agePosition]+"-12-31 23:59:59";
        }
        nowpage = 1;
        ApiGetData(startDate,endDate);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        isVisible = false;
    }

    @OnClick(R.id.select_ll)
    public void onViewClicked() {
        ageDialog();
    }
}
